local skynet = require "skynet"
local cluster = require "cluster"
local socket = require "socket"
local gate_info = {}
local gate_init = {}
local CMD = {}
local oldtime = 0

function clearwin()
    print("\27[0;0H")
end
function print_info()
    local msg1=string.format("     %-25s%16s%16s","          gate","links","t(ms)")
    local msg=""
    for i=1,#gate_init do
        for k,v in pairs(gate_info) do
            if gate_init[i] == v.addr then
                skynet.error(v.addr,v.num,v.time_out)
                local str = string.format("     %-25s%16s          %-16s\n",tostring(k),tostring(v.num),tostring(v.time_out)) 
                msg = msg..str
            end
        end
    end
    clearwin()
    print(msg1)
    print(msg)
end

function CMD.data(info)
    gate_info[info.addr]=info
end

function screen()
    while true do
        print_info()
        skynet.sleep(200)
    end
end

function getaddr(addr)
    local pos=1,pos_temp
    local flag=0
    local gate_dst={}
    while true do
        pos_temp=pos
        pos=string.find(addr,";",pos+1)
        if  not pos then
            break
        end
        if flag>0 then
            pos_temp=pos_temp+1
        end
        getaddr=string.sub(addr,pos_temp,pos-1)
        table.insert(gate_dst,getaddr)
        flag=flag+1
    end 
    return gate_dst
end

function CMD.start(conf)
    local gatedst=getaddr(conf.gatedst)   
    local index = 1
    for k,v in pairs(gatedst) do
        local pos=string.find(v,":",1)
        local ip_=string.sub(v,1,pos-1)
        local port_=tonumber(string.sub(v,pos+1))
        local getgateinfo=skynet.newservice("getgateinfo")
        skynet.send(getgateinfo, "lua", "start",{ip=ip_,port=port_,mainserver=conf.server})
        local addr=ip_..":"..port_
        gate_info[addr]={addr=addr,num=0,time_out=0}
        gate_init[index]=addr
        index = index + 1
        skynet.error("start: "..addr)
     end    
    os.execute("clear")
    skynet.fork(screen) 
end


skynet.start(function()
    skynet.dispatch("lua", function(session, source, cmd, subcmd, ...)
		local f = assert(CMD[cmd])
		skynet.ret(skynet.pack(f(subcmd, ...)))
	end)
    skynet.error("mainserver start...")
    math.randomseed(os.time())
end)
